var util = require('../../utils/util.js');
import * as echarts from '../../ec-canvas/echarts';

var chart = null;

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: app.globalData.userInfo,
    currentData: 0,
    array: [

    ],
    start_time: util.formatDate(new Date()),
    end_time: util.formatDate(new Date()),
    jlr: "",
    // jlr_array: ['炳', '妍'],
    // jlr_index: 0,
    // jlr_df: '请选择',
    jlr_items: [

    ],
    sum: '0',
    ec: {
      lazyLoad: true // 延迟加载
    },
    clientHeight: '',
    ifInit: false,
    sz_items: [{
        name: '-',
        value: '支出',
        checked: 'true'
      },
      {
        name: '+',
        value: '收入'
      }
    ],
    shouzhi: '-',
  },

  //初始化图表
  init_echarts: function () {
    this.echartsComponnet.init((canvas, width, height) => {
      // 初始化图表
      chart = echarts.init(canvas, null, {
        width: width,
        height: height
      });

      chart.clear(); // 清除
      chart.setOption(option); //获取新数据
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return chart;
    });
  },

  init: function () {
    var that = this;

    if (that.data.ifInit)
      return true;

    that.setData({
      // userInfo: wx.getStorageSync("userInfo")
      userInfo: app.globalData.userInfo
    });

    if (that.data.userInfo == undefined || that.data.userInfo == {} || that.data.userInfo == "") {
      wx.showToast({
        title: '请先在主页点击授权',
        icon: 'none',
        duration: 3000
      });
    } else {
      that.setData({
        ifInit: true
      });
      return true;
    }
    return false;
  },

  //获取当前滑块的index
  bindchange: function (e) {
    const that = this;
    that.setData({
      currentData: e.detail.current
    })
  },

  //点击切换，滑块index赋值
  checkCurrent: function (e) {
    const that = this;

    if (that.data.currentData === e.target.dataset.current) {
      return false;
    } else {

      that.setData({
        currentData: e.target.dataset.current
      })
    };
  },

  getGroupMember: function () {
    var postObj = {
      "OPENID": "\"" + wx.getStorageSync("openid") + "\""
    };

    wx.request({
      url: wx.getStorageSync("sURL"),
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      data: {
        url: '/webUserView',
        postdata: JSON.stringify(postObj)
      },
      method: 'POST',
      success: res => {
        console.log(res);
        var str = res.data.result;
        var str2 = JSON.parse(str);
        var rw = str2["rows"];

        var group = rw[0]["DIARY_GROUP"];
        var members = (group || '').split(",");
        var inStr = '';
        //初始化,DIARY_GROUP里是包含自己的
        var items = [];

        members.forEach(function (item, index) {

          inStr += "\"" + item + "\"";
          if (index != members.length && index != 1) {
            inStr += ','
          }
        });
        if (inStr != '') {
          var postObj2 = {
            "OPENID": inStr
          };
          wx.request({
            url: wx.getStorageSync("sURL"),
            header: {
              'content-type': 'application/x-www-form-urlencoded' // 默认值
            },
            data: {
              url: '/webUserView',
              postdata: JSON.stringify(postObj2)
            },
            method: 'POST',
            success: res => {
              var str3 = JSON.parse(res.data.result);
              var rw3 = str3["rows"];

              //轮询获得微信账号名称
              rw3.forEach(function (item, index) {
                var self3 = {};
                self3.name = item["OPENID"];
                self3.value = item["NICKNAME"];
                self3.checked = true;
                items.push(self3);
              });

              this.setData({
                jlr_items: items,
                jlr: inStr
              });
            }
          });
        }
      }
    })
  },

  showDiary: function () {
    var postObj = {
      "start_time": this.data.start_time,
      "end_time": this.data.end_time,
      "creator_id": this.data.jlr == '' ? "\"" + wx.getStorageSync("openid") + "\"" : this.data.jlr,
      "in_out": this.data.shouzhi,
    };

    wx.request({
      url: wx.getStorageSync("sURL"),
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      data: {
        url: '/getExpQuery',
        postdata: JSON.stringify(postObj)
      },
      method: 'POST',
      success: res => {
        console.log(res);
        var str = res.data.result;
        var str2 = JSON.parse(str);
        var rw = str2["rows"];
        this.setData({
          array: rw
        });
      }
    });

    //获得分类统计图
    wx.request({
      url: wx.getStorageSync("sURL"),
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      data: {
        url: '/getExpSumByCategory',
        postdata: JSON.stringify(postObj)
      },
      method: 'POST',
      success: res => {
        console.log(res);
        var str = res.data.result;
        var str2 = JSON.parse(str);
        var rw = str2["rows"];

        var windowWidth = 320;
        try {
          var res = wx.getSystemInfoSync();
          windowWidth = res.windowWidth;
        } catch (e) {
          console.error('getSystemInfoSync failed!');
        }

        option.series[0].data = rw;
        console.log(option);

        var that = this;
        that.init_echarts();
      }
    });
  },

  getSum: function () {
    var postObj = {
      "start_time": this.data.start_time,
      "end_time": this.data.end_time,
      "creator_id": this.data.jlr == '' ? "\"" + wx.getStorageSync("openid") + "\"" : this.data.jlr,
      "in_out": this.data.shouzhi,
    };

    wx.request({
      url: wx.getStorageSync("sURL"),
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      data: {
        url: '/getExpSum',
        postdata: JSON.stringify(postObj)
      },
      method: 'POST',
      success: res => {
        console.log(res);
        var str = res.data.result;
        var str2 = JSON.parse(str);
        var rw = str2["rows"];
        this.setData({
          sum: rw[0]["sum"]
        });
      }
    })
  },

  addIPayBtn: function (options) {
    wx.navigateTo({
      url: '../addIPay/addIPay'
    })
  },

  queryIPayBtn: function (options) {
    var that = this;
    that.showDiary();
    that.getSum();
  },

  st_bindDateChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value);
    this.setData({
      start_time: e.detail.value
    })
  },

  et_bindDateChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value);
    this.setData({
      end_time: e.detail.value
    })
  },

  // bindJlrChange: function (e) {
  //   console.log('bindJlrChange发送选择改变，携带值为', e.detail.value);
  //   let i = e.detail.value;
  //   let array = this.data.jlr_array;
  //   this.setData({
  //     jlr_index: i,
  //     jlr_df: array[i],
  //     jiluren: array[i]
  //   });
  // },

  jlr_checkboxChange: function (e) {
    var s = e.detail.value;
    var v = '';
    for (var index in s) {
      v += "\"" + s[index] + "\"" + ','
    };
    this.data.jlr = v.substring(0, v.length - 1);
    console.log('jlr_checkbox发生change事件，携带value值为：', e.detail.value);
  },

  //类型单选
  sz_radioChange: function (e) {
    this.setData({
      shouzhi: e.detail.value
    });
    console.log(this.data.shouzhi);
    console.log('radio发生change事件，携带value值为：', e.detail.value);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    if (that.init()) {
      // that.getGroupMember();
      // that.showDiary();
      // that.getSum();

      this.echartsComponnet = this.selectComponent('#mychart');

      if (!chart) {
        that.init_echarts(); //初始化图表
      } else {
        // chart.clear();  // 清除
        // // chart.setOption(that.getOption());  //获取新数据
        // chart.setOption(that.option);  //获取新数据
        chart.clear(); // 清除
        chart.setOption(option); //获取新数据
      }

      wx.getSystemInfo({
        success: function (res) {
          that.setData({
            clientHeight: res.windowHeight - 177
          });
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    if (that.init()) {
      if (that.data.jlr_items == undefined || that.data.jlr_items.length == 0) {
        that.getGroupMember();
      }
      setTimeout(function () {
        that.showDiary();
        that.getSum();
      }, 300)
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
});

var option = {
  title: {
    text: '各分类占比图',
    left: 'center'
  },
  tooltip: {
    trigger: 'item',
    formatter: '{b} {c} ({d}%)' //{a} <br/>
  },
  legend: {
    left: 'center',
    top: 'bottom',
  },
  toolbox: {
    show: false,
    feature: {
      mark: {
        show: true
      },
      dataView: {
        show: true,
        readOnly: false
      },
      magicType: {
        show: true,
        type: ['pie', 'funnel']
      },
      restore: {
        show: true
      },
      saveAsImage: {
        show: true
      }
    }
  },
  series: [{
    name: '分类',
    type: 'pie',
    radius: [30, 100],
    center: ['50%', '50%'],
    roseType: 'area',
    data: []
  }]
};